package org.transfer.service;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.transfer.model.FinanceTemplate;
import org.transfer.model.ImportLog;
import org.transfer.model.RegisterTable;
import org.transfer.utils.ConfigUtil;
import org.transfer.utils.FileUtils;
import org.transfer.utils.LogUtils;

@Component
public class FilterFileService {

	@Autowired
	private RegisterTableService registerTableService;
	@Autowired
	private ImportLogService importLogService;

	private String logPath = "";

	/**
	 * 过滤加密文件找到对应模板
	 * 
	 * @throws IOException
	 */
	public void filterFile() throws IOException {
		System.out.println("===================过滤开始===================");
		String filePath = ConfigUtil.getConfigure().getProperty("filePath");
		String decryptPath = ConfigUtil.getConfigure().getProperty("decryptPath");
		String logsFile = ConfigUtil.getConfigure().getProperty("logsFile");
		File logFile = new File(logsFile);
		if (!logFile.exists()) {
			logFile.mkdirs();
		}
		logPath = logsFile + "filter.log";
		List<File> list = new ArrayList<File>();
		scanningFile(list, filePath);
		List<File> inputList = new ArrayList<File>();
		scanningFile(inputList, decryptPath);

		for (File file : list) {
			String fileName = file.getName().toUpperCase();
			if (!(fileName.indexOf(".") != -1 && (fileName.indexOf("7Z") != -1 || fileName.indexOf("GPG") != -1)
					&& ("7Z".equals(fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()))
							|| "GPG".equals(fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())))
					&& fileName.indexOf("_") != -1 && fileName.split("_").length == 5)) {
				LogUtils.logs(logPath, "【" + file.getName() + "】文件格式不合法");
				continue;
			}
			// 过滤不处理预算执行数据
			if (fileName.indexOf("预算") != -1) {
				LogUtils.logs(logPath, "【" + file.getName() + "】预算执行无需过滤");
				continue;
			}
			// 需要过滤状态
			boolean flag = true;
			// 判断如果输出文件夹有该文件则无需过滤
			for (File inputFile : inputList) {
				if (inputFile.getName().equals(file.getName())) {
					flag = false;
					break;
				}
			}
			if (!flag) {
				LogUtils.logs(logPath, "【" + file.getName() + "】无需过滤");
				continue;
			}
			String[] fileNames = file.getName().split("_");
			String area = fileNames[0];
			String code = fileNames[1];
			String name = fileNames[2];
			String sysName = "";
			// 查询登记表模板
			RegisterTable registerTable = new RegisterTable();
			registerTable.setAreaCode(area);
			registerTable.setCompanyCode(code);
			registerTable.setCompanyName(name);
			sysName = registerTableService.findFinanceName(registerTable);
			if (StringUtils.isNotBlank(sysName)) {
				List<FinanceTemplate> templateList = registerTableService.findTemplateList(sysName, "");
				ImportLog entity = importLogService
						.get(new ImportLog(file.getName().substring(0, file.getName().indexOf("."))));
				if (entity != null && entity.getLastImportDate() != null
						&& file.lastModified() <= Long.valueOf(entity.getLastImportDate())) {
					LogUtils.logs(logPath, "【" + file.getName() + "】无需过滤");
					continue;
				}
				// 保存日志信息
				ImportLog importLog = new ImportLog();
				if (entity != null) {
					importLog.setId(entity.getId());
				}
				importLog.setIp(ConfigUtil.getHostIp());
				importLog.setAreaCode(area);
				importLog.setCompanyCode(code);
				importLog.setCompanyName(name);
				importLog.setFileName(file.getName().substring(0, file.getName().indexOf(".")));
				importLog.setLastImportDate(String.valueOf(file.lastModified()));
				importLog.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				importLog.setFilterState("1");
				importLog.setDataType("财务");
				importLog.setFilterMsg("通过过滤");
				if (templateList == null || templateList.size() <= 0) {
					LogUtils.logs(logPath, "【" + file.getName() + "】系统中未找到登记表模板");
					importLog.setFilterState("0");
					importLog.setFilterMsg("系统中未找到登记表模板");
					importLogService.save(importLog);
					continue;
				}
				importLogService.save(importLog);
				try {
					FileUtils.copyFile(file.getPath(), decryptPath + file.getName());
					System.out.println("---------【" + file.getName() + "】过滤完毕！----------");
					LogUtils.logs(logPath, "【" + file.getName() + "】过滤完成");
				} catch (Exception e) {
					LogUtils.logs(logPath, "【" + file.getName() + "】过滤失败");
				}
			} else {
				LogUtils.logs(logPath, "【" + file.getName() + "】单位信息未找到登记表信息");
				continue;
			}

		}
		System.out.println("===================过滤结束===================");
	}

	/**
	 * 获取加密文件集合
	 * 
	 * @param list
	 * @param filePath
	 * @return
	 */
	public List<File> scanningFile(List<File> list, String filePath) {
		File document = new File(filePath);
		if (!document.exists()) {
			document.mkdirs();
		}
		if (!document.isFile()) {
			File[] files = document.listFiles();
			for (File file : files) {
				scanningFile(list, file.getPath());
			}
		} else {
			list.add(document);
		}
		return list;
	}

}
